Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
Attempting to retrieve JSON data results in [ Promise { <pending> }, Promise { <pending> } ]

I am attempting to retrieve the JSON data stored in the following API:

https://api.hatchways.io/assessment/blog/posts

Using node.js and https requests, I constantly receive an array of [ Promise { }, Promise { } ]. Unfortunately, I can only search by one tag at a time, and I have to retrieve a list of posts that has at least one tag from a list of provided tags, before sorting the posts. My code is below:

const express = require('express');
const app = express();

app.get("/api/ping", (req, res) => {
    res.status(200).send("{\"success\": true}");
})

app.get("/api/posts", (req, res) => {
    const tags = req.query.tags;
    const sortBy = req.query.sortBy;
    const direction = req.query.direction;

    if (!tags) res.status(400).send("Must provide at least one tag.");
    let tag_array = tags.split(',');
    let posts_array = [];
    tag_array.forEach(tag => {
        let posts = getPost(tag);
        posts_array.push(posts);
    })
    
    console.log(posts_array);
})

app.listen(3000, () => console.log("Listening on port 3000..."));

function getPost(tag) {
    const https = require('https');

    return new Promise( (resolve, reject) => {
        const options = {
            hostname: 'api.hatchways.io',
            path: `/assessment/blog/posts?tag=${tag}`
        }
    
        let body = [];

        const req = https.request(options, res => {
            res.on('data', data => {
                body.push(data);
            });

            res.on('end', () => {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch (error) {
                    reject(error);
                }
                resolve(body);
            });
        });
    
        req.on('error', error => {
            reject(error);
        });
    
        req.end();
    }).then(function(data) { return data; }, function(error) { console.log(error) });
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

the getPost method is returning a promise, just do this:

app.get("/api/posts", async (req, res) => {
    const tags = req.query.tags;
    const sortBy = req.query.sortBy;
    const direction = req.query.direction;

    if (!tags) res.status(400).send("Must provide at least one tag.");
    let tag_array = tags.split(',');
    const promises = [];
    tag_array.forEach(tag => {
        promises.push(getPost(tag))
    });
    posts_array = await Promise.all(promises)
    console.log(posts_array)
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

Just wait for all promises to resolve using the await keyword.

app.get("/api/posts", async (req, res) => { // Add the async keyword

    //... Skipped some code for concision
    
    tag_array.forEach(tag => {
        let posts = getPost(tag);
        posts_array.push(posts);
    })
    
    await Promise.all(posts_array)    // Add this to await all promises to resolve
    console.log(posts_array);
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda